package com.nextbus.parser;

/**
 * 读取本地文件提取信息
 */
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;

import javax.xml.parsers.ParserConfigurationException;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import android.content.Context;
import android.util.Log;
import android.util.Xml.Encoding;

import com.nextbus.database.DatabaseHelper;
import com.nextbus.main.UpdateAsyncTask;
import com.nextbus.model.Direction;
import com.nextbus.model.DirectionsAndStops;
import com.nextbus.model.Route;
import com.nextbus.model.RouteConfig;
import com.nextbus.model.Stop;

public class RouteConfigFeedParser extends DefaultHandler {
    private static final String TAG = "RouteConfigFeedParser";

    // 解析routeconfig用到的变量
    // 全部站点，不重复的，没有冗余站点
    // private HashSet<Stop> sharedStops;
    /*
     * private HashSet<String> sharedStops; private ArrayList<HashMap<String,
     * Stop>> stops; //全部路线的信息 private ArrayList<Route> routes;
     * 
     * //全部路线的方向集合 private ArrayList<Direction> directions; //一条路线包含多个站点 private
     * HashMap<String, String> routeKeyToStopKey; //route包含多个站点，全部route对应的站点
     * private ArrayList<HashMap<String, String>> routeToStopmapping;
     */
    // 进入一个Route设为true，出去Route设为false；
    // 解析routeconfig，往往会用到route，所以设置个全局变量

    // 一个站点的信息
    private Route route;

    private HashMap<String, String> routeToStopmapping;

    private ArrayList<Stop> stops;

   // private ArrayList<Direction> directions;

    private ArrayList<DirectionsAndStops> directionsToStopsMapping;
    
    private DirectionsAndStops directonToStopsMapping;
    
    private Direction direction;
    
    private ArrayList<String> stopsMapping;

    // 站点信息链表
    private ArrayList<RouteConfig> routeConfigs;

    // 用来过滤相同站点
    private HashSet<String> shareStops;

    private String routeTag;

    // 公共变量
    private DatabaseHelper helper;

    public RouteConfigFeedParser(Context context) {
        super();
        helper = new DatabaseHelper(context);
    }

    /**
     * runParse更加简单
     * 
     * @param inputStream
     * @throws ParserConfigurationException
     * @throws SAXException
     * @throws IOException
     */
    public void runParse(InputStream inputStream)
            throws ParserConfigurationException, SAXException, IOException {
        android.util.Xml.parse(inputStream, Encoding.UTF_8, this);
    }

    @Override
    public void startDocument() throws SAXException {
        shareStops = new HashSet<String>();
        routeConfigs = new ArrayList<RouteConfig>();
 
    }

    @Override
    public void startElement(String uri, String localName, String qName,
            Attributes attributes) throws SAXException {
        //System.out.println("localName : " + localName );
        if (localName.equals("route")) {
            routeTag = attributes.getValue("tag");
            String color = attributes.getValue("color");
            String oppositeColor = attributes.getValue("oppositeColor");

            route = new Route(routeTag, color, oppositeColor);
            routeToStopmapping = new HashMap<String, String>();
            stops = new ArrayList<Stop>();
            //directions = new ArrayList<Direction>();
            directionsToStopsMapping = new ArrayList<DirectionsAndStops>();
        }

        if (localName.equals("stop")) {
            if (attributes.getValue("title") != null) {
                String tag = attributes.getValue("tag");
                routeToStopmapping.put(tag, routeTag);
                if (shareStops.contains(tag) == false) {
                    shareStops.add(tag);
                    String lat = attributes.getValue("lat");
                    String lon = attributes.getValue("lon");
                    String title = attributes.getValue("title");
                    Stop stop = new Stop(tag, lat, lon, title);
                    stops.add(stop);
                }
            } else {
                stopsMapping.add(attributes.getValue("tag"));
            }

        }

        if (localName.equals("direction")) {
            String dirTag = attributes.getValue("tag");
            String name = attributes.getValue("name");
            String title = attributes.getValue("title");
            direction = new Direction(dirTag, name, title, routeTag);
            stopsMapping = new ArrayList<String>();
        }
    }

    @Override
    public void endElement(String uri, String localName, String qName)
            throws SAXException {

        if (localName.equals("route")) {
            RouteConfig routeConfig = new RouteConfig(route,
                    routeToStopmapping, stops, directionsToStopsMapping);
            routeConfigs.add(routeConfig);
        }
        
        if (localName.equals("direction")) {
            directonToStopsMapping = new DirectionsAndStops(direction, stopsMapping);
            directionsToStopsMapping.add(directonToStopsMapping);
        }
    }

    @Override
    public void endDocument() throws SAXException {
        super.endDocument();
    }

    public void writeInitDataToDB(UpdateAsyncTask publisher) {
        /* helper.writeInitDataToDB(dataContent, publisher); */
        if (!helper.writeAllRouteConfigDataToDB(routeConfigs, publisher)) {
            Log.d(TAG, "error may occur @ writeAllRouteConfigDataToDB");
        }
    }

}
